<template>
  <BasicModal
    v-bind="$attrs"
    okText="修改"
    @register="registerModal"
    title="修改基本信息"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #avatar>
        <CropperAvatar
          width="100"
          :uploadApi="updateAvatar"
          @change="userStore.getUserInfoAction"
          :value="getUserInfo.avatar"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { unref, computed } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { useMessage } from '@/hooks/web/useMessage';
  import { updateBase, updateAvatar } from '@/api/sys/user';
  import { CropperAvatar } from '@/components/Cropper';
  import { useUserStore } from '@/store/modules/user';
  import formValidation from '@/utils/vaidator';

  const emit = defineEmits(['success', 'register']);

  const resetForm: FormSchema[] = [
    {
      field: 'avatar',
      label: '头像',
      component: 'Input',
      slot: 'avatar',
    },
    {
      field: 'name',
      label: '昵称',
      component: 'Input',
      required: true,
    },
    {
      field: 'email',
      label: '邮箱地址',
      component: 'Input',
      required: true,
      rules: [{ validator: formValidation.email.rule }],
    },
  ];
  const userStore = useUserStore();
  const getUserInfo = computed(() => {
    const { name, avatar, desc, email } = userStore.getUserInfo || {};
    return { name, avatar, desc, email };
  });
  const { createMessage } = useMessage();
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: resetForm,
    showActionButtonGroup: false,
    baseColProps: { span: 24 },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async () => {
    resetFields();
    setFieldsValue(unref(getUserInfo));
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      await updateBase(values);
      // 刷新用户信息
      userStore.getUserInfoAction();
      createMessage.success('修改成功');
      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
